//
//  TimerView.swift
//  ClassManager
//
//  Created by wqh on 1/27/21.
//

import SwiftUI

struct TimerView: View {
    @EnvironmentObject var UserData: CoreData
    @Environment(\.colorScheme) var ColorMode: ColorScheme
    @Binding var show: [Bool]
    @State var width: CGFloat? = nil
    @State var height: CGFloat? = nil
    @State var time: CGFloat = CGFloat(Int(Date().timeIntervalSince1970.string(format: "mm"))!) / 60
    @State var now = Date().timeIntervalSince1970
    @State var timer = Timer.TimerPublisher(interval: 5, runLoop: .current, mode: .default).autoconnect()
    var body: some View {
        if show[0] {
            DispatchQueue.main.async {
                withAnimation(.spring()) {
                    width = 0
                }
            }
        }
        if show[2] {
            DispatchQueue.main.async {
                withAnimation(.spring()) {
                    height = 0
                }
            }
        }
        if !show[0] && !show[1] && !show[2] {
            DispatchQueue.main.async {
                withAnimation(.spring()) {
                    width = nil;height = nil
                }
            }
        }
        return Rectangle()
            .cornerRadius(15)
            .shadow(radius: 30, x: 5, y: 5)
            .foregroundColor(ColorMode == .dark ? Color.white.opacity(0.2):.white)
            .frame(width: width, height: height)
            .overlay(
                VStack(alignment: .center) {
                    if width != 0 && height != 0 {
                        HStack {
                            Text("\(show[1] ? "上课禁用":"现在时间")")
                                .font(.title)
                                .fontWeight(.semibold)
                            Spacer()
                        }
                        if show[1] {
                            ForEach(UserData.events) { _event in
                                if Int((_event.start - now)/60)<=0 && Int((_event.end - now)/60)>=0 && !_event.isRemoved {
                                    ProgressView("", value: last(now: now, start: _event.start , end: _event.end) >= 0 ?
                                                    last(now: now, start: _event.start , end: _event.end):0
                                    , total: 1)
                                        .progressViewStyle(RoundedProgressViewStyle {
                                            Text(UserData.classes[_event._class].name)
                                                .font(Font.system(size: 150))
                                            Text("任课老师：\(_event.techer)")
                                                .font(.largeTitle)
                                            Text(Int((_event.end - now)/60) == 0 ?
                                                    "离下课还有不到一分钟":"离下课还有\(Int((_event.end - now)/60))分钟")
                                                .font(.largeTitle)
                                                .onReceive(timer) { _ in
                                                    withAnimation(.default) {
                                                        now = Date().timeIntervalSince1970
                                                        if (_event.end - now)/60 < 0 {
                                                            show[0] = false;show[1] = false;show[2] = false
                                                        }
                                                    }
                                                }
                                        })
                                }
                            }
                        }
                        else {
                            ProgressView("", value: time*100, total: 100)
                                .progressViewStyle(RoundedProgressViewStyle {
                                    ForEach(UserData.events) { _event in
                                        if Int((_event.start - now)/60) <= 5 && (_event.end - now)/60 >= 0 && !_event.isRemoved {
                                            Text("\(Int((_event.start - now)/60)<0 ? "":"距离下一节课")")
                                            Text(UserData.classes[_event._class].name)
                                                .font(.title)
                                            if (_event.start - now)/60 <= 0 {
                                                Text("已上课")
                                            }
                                            else if (_event.start - now)/60 <= 1 {
                                                Text("只剩不到一分钟")
                                            }
                                            else {Text("只剩\(Int((_event.start - now)/60))分钟")}
                                        }
                                    }
                                    Text(Date().timeIntervalSince1970.string(format: "hh:mm"))
                                        .font(.largeTitle)
                                })
                                .onReceive(timer) { _ in
                                    withAnimation(.default) {
                                        self.time = timeOfDay()
                                    }
                                    self.now = Date().timeIntervalSince1970
                                    //                                // print(self.time)
                                }
                        }
                    }
                    Spacer()
                }.padding()
                .frame(width: width, height: height)
            )
    }
    private func timeOfDay() -> CGFloat {
        let time = CGFloat(Int(Date().timeIntervalSince1970.string(format: "mm"))!)
        return time / 60
    }
    private func ToggleShows(_ index: Int) {
        for i in 0..<self.show.count {
            self.show[i] = (i == index) ? true:false
        }
    }
    private func last(now: TimeInterval, start: TimeInterval, end: TimeInterval) -> CGFloat {
        let past = (end - now)/60, length = (end - start)/60
        return CGFloat(past/length)
    }
}
